package wili.json.xml;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Element;
import org.dom4j.Node;

import wili.json.JsonNode;

/**
 * 
 * @author weilai
 *
 */
public class XmlTag {
	public final int id = ++GenID;
	public final String name;
	public List<String[]> atts;
	public List<XmlTag> sons;
	public String text;
	public final Element element;

	public String toString() {
		return element.asXML();
	}

	public XmlTag(Node ele) {
		this.element = (Element) ele;
		this.name = ele.getName();
		//		Iterator<Attribute> aa = ele.attributeIterator();
		//		while (aa.hasNext()) {
		//			Attribute att = aa.next();
		//			this.addAtt(att.getName(), att.getStringValue());
		//		}

	}

	public static void sortByName(List<XmlTag> sons) {
		Collections.sort(sons, new Comparator<XmlTag>() {
			@Override
			public int compare(XmlTag o1, XmlTag o2) {
				return o1.name.compareToIgnoreCase(o2.name);
			}
		});
	}

	public List<XmlTag> sons() {
		if (sons == null) {
			int ct = element.nodeCount();
			sons = new ArrayList<>(ct);
			Iterator<Element> it = element.elementIterator();
			while (it.hasNext()) {
				Element son = it.next();
				this.addSon(new XmlTag(son));
			}
		}
		return sons;
	}

	public XmlTag son(String tag) {
		Element ret = element.element(tag);
		return new XmlTag(ret);
	}

	/**
	 * 属性名集 ~>属性集
	 */
	public List<XmlTag> getAtts(boolean sort, String... atts) {
		List<XmlTag> ret = null;
		for (String att : atts) {
			XmlTag at = this.son(att);
			if (at != null) {
				if (ret == null)
					ret = new ArrayList<>(atts.length);
				ret.add(at);
			}
		}
		if (sort)
			XmlTag.sortByName(ret);
		return ret;
	}

	public String valueOfAtt(String att) {
		element.asXML();
		return element.attribute(att).getStringValue();
	}

	public void setAtt(String att, String value) {
		element.attribute(att).setValue(value);
	}

	public String getText() {
		return element.getText();
	}

	public void setText(String value) {
		element.setText(value);
	}

	public XmlTag(String name, String... atts) {
		this.element = null;
		this.name = name;
		for (int i = 0; i < atts.length; i += 2) {
			this.addAtt(atts[i], atts[i + 1]);
		}
	}

	public void addSon(String name, String... atts) {
		XmlTag son = new XmlTag(name, atts);
		addSon(son);
	}

	public void addSon(XmlTag tag) {
		if (element != null) {
			Element ele = element.addElement(tag.name);

			return;
		}
		if (sons == null)
			sons = new ArrayList<>();
		sons.add(tag);
	}

	public void addAtt(String name, String va) {
		if (element != null) {
			element.addAttribute(name, va);
			return;
		}
		if (atts == null)
			atts = new ArrayList<>();
		atts.add(new String[] { name, va });
	}

	static int GenID;
}
